<template>
    <div class="table">
        <div class="crumbs">
            <el-breadcrumb separator="/">
                <el-breadcrumb-item>
                    <i class="el-icon-date"></i>{{$route.name}}
                </el-breadcrumb-item>
            </el-breadcrumb>
        </div>
        <div class="handle-box">
            <el-dialog :title="title" :visible.sync="dialogFormVisible">
                <el-form :model="addForm" :rules="rules" ref="addForm">
                    <el-form-item label="发布时间" :label-width="formLabelWidth">
                        <el-date-picker v-model="addForm.publicAt" type="date" value-format="yyyy-MM-dd" placeholder="选择日期">
                        </el-date-picker>
                    </el-form-item>
                    <el-form-item label="标题" :label-width="formLabelWidth" prop="title">
                        <el-input type="text" v-model="addForm.title" auto-complete="off"></el-input>
                    </el-form-item>
                    <el-form-item label="作者" :label-width="formLabelWidth">
                        <el-input type="text" v-model="addForm.author" auto-complete="off"></el-input>
                    </el-form-item>
                    <el-form-item label="来源" :label-width="formLabelWidth">
                        <el-input type="text" v-model="addForm.origin" auto-complete="off"></el-input>
                    </el-form-item>
                    <el-form-item label="内容" :label-width="formLabelWidth">
                        <editor @input="htmlOutput" :htmlContent="addForm.content"></editor>
                    </el-form-item>
                    <el-form-item label="附件" :label-width="formLabelWidth">
                        <el-upload
                            action=""
                            :http-request="upload"
                            :on-remove="handleRemove"
                            :before-remove="beforeRemove"
                            :file-list="fileList"
                        >
                            <el-button size="small" type="primary">点击上传</el-button>
                        </el-upload>
                    </el-form-item>
                </el-form>
                <div slot="footer" class="dialog-footer">
                    <el-button @click="dialogFormVisible = false">取 消</el-button>
                    <el-button type="primary" @click="add">确 定</el-button>
                </div>
            </el-dialog>
            <el-input placeholder="输入标题" v-model="searchKey" class="search"></el-input>
            <el-button type="primary" icon="search" @click="search">搜索</el-button>
            <el-button type="primary" @click="addType">新增下载文件</el-button>
        </div>
        <div>
          <el-table :data="tableData" border fit style="width: 100%">
              <el-table-column prop="publicAt" label="发布时间" show-overflow-tooltip :formatter="timeFormatter">
              </el-table-column>
              <el-table-column prop="title" label="标题" show-overflow-tooltip>
              </el-table-column>
              <el-table-column prop="author" label="作者" show-overflow-tooltip>
              </el-table-column>
              <el-table-column prop="origin" label="来源" show-overflow-tooltip>
              </el-table-column>
              <el-table-column prop="content" label="内容" show-overflow-tooltip>
              </el-table-column>
              <el-table-column prop="attach_name" label="附件" show-overflow-tooltip>
              </el-table-column>
              <el-table-column fixed="right" label="操作">
                  <template slot-scope="scope">
                      <el-button type="text" size="small" @click="edit(scope.row)">编辑</el-button>
                      <el-button type="text" size="small" @click="delNotice(scope.row)">删除</el-button>
                  </template>
              </el-table-column>
          </el-table>
        </div>
        <div class="block">
            <el-pagination @current-change="handleCurrentChange" 
            :current-page="page.number" layout="total, prev, pager, next, jumper" 
            :total="page.total">
            </el-pagination>
        </div>
    </div>
</template>
<script>
import Editor from './../../components/common/Editor';
import { download, uploadFile } from "../../server/getDate.js";
import { mapState, mapActions } from 'vuex'
import { getStore, dateFormatter, filterObj } from '../../utils/local.js'
import { confirm } from '../../utils/local'
const { listApi, addApi, deleteApi, updateApi } = download
export default {
    data() {
        return {
            loading: false,
            dialogFormVisible: false,
            title: '',
            addForm: {},
            formLabelWidth: '120px',
            searchKey: '',
            rules: {
                title: [{ required: true, message: '请输入标题', trigger: 'blur' }]        
            },
            fileList: []
        }
    },
    components: {
        Editor
    },
    created() {
        this.getList(1)
    },
    computed: mapState({
        tableData: state => state.Download.data,
        page: state => state.Download.page
    }),
    methods: {
        ...mapActions(['saveData']),
        getList(number) {
            const params = {
                page: number,
                pageSize: 10
            }
            if (this.searchKey !== '') {
                params.searchKey = this.searchKey
            }
            listApi({ ...params }).then(res => {
                if (res.code === '000000') {
                    this.saveData({
                        ...res,
                        number
                    })
                } else {
                    this.$message.error(res.message)
                }
            }, () => {
                this.$message.error('网络错误')
            })
        },
        htmlOutput(html) {
            this.addForm.content = html
        },
        addType(){
            this.dialogFormVisible = true
            this.title = '新增下载文件'
            this.addForm = {}
            this.fileList = []
        },
        edit(row) {
            this.dialogFormVisible = true
            this.title = '修改下载文件'
            this.addForm = filterObj(row)
            if (dateFormatter(row.publicAt)) {
                this.addForm.publicAt = dateFormatter(row.publicAt)
            }
            this.fileList = []
            if (row.attach_name && row.attach_url) {
                this.fileList.push({
                    name: row.attach_name,
                    url: row.attach_url
                })
            }
        },
        delNotice(row) {
            this.$confirm('此操作将永久删除该信息, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                deleteApi({ ids: row.id }).then(res => {
                    if (res.code === '000000') {
                        this.$message({
                            type: 'success',
                            message: '删除成功!'
                        }); 
                        this.getList(this.page.number)    
                    } else {
                        this.$message.error(res.message)
                    }
                }, () => {
                    this.$message.error('网络错误')
                })
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消删除'
                });
            });
        },
        add(){
            if (this.fileList && this.fileList.length > 0) {
                this.addForm.attachName = this.fileList[0].name
                this.addForm.attachUrl = this.fileList[0].url
            } else {
                delete this.addForm.attachName
                delete this.addForm.attachUrl
            }
            this.$refs['addForm'].validate(valid => {
                if (valid) {
                    this.dialogFormVisible = false
                    if (this.addForm.id) {
                        updateApi({ ...this.addForm }).then(res => {
                            if (res.code === '000000') {
                                this.$message.success('修改成功')
                                this.getList(this.page.number)
                            } else {
                                this.$message.error(res.message)
                            }
                        }, () => {
                            this.$message.error('网络错误')
                        })
                    } else {
                        addApi({ ...this.addForm }).then(res => {
                            if (res.code === '000000') {
                                this.$message.success('添加成功')
                                this.getList(this.page.number)
                            } else {
                                this.$message.error(res.message)
                            }
                        }, () => {
                            this.$message.error('网络错误')
                        })
                    }
                }
            })
        },
        timeFormatter(row) {
            return dateFormatter(row.publicAt)
        },
        handleCurrentChange(val) {
            this.getList(val)
        },
        search() {
            this.getList(this.page.number)
        },
        upload(val) {
            this.fileList = []
            let formData = new FormData()
            formData.append('fileName', val.file);
            formData.append('fileType', '2')
            uploadFile(formData, res => {
                if (res.code === '000000') {
                    this.fileList.push({
                        name: res.result.originName,
                        url: res.result.storageName
                    })
                } else {
                    this.$message.error(res.message)
                }
            })
        },
        handleRemove(file, fileList) {
            this.fileList = this.fileList.filter(item => {
                return item.name !== file.name
            })
        },
        beforeRemove(file, fileList) {
            return this.$confirm(`确定移除 ${ file.name }？`);
        },
  }
}
</script>
<style lang="scss" scoped>
.handle-box {
  margin-bottom: 1%;
  .search {
    width: 30%;
  }
}

.block {
  text-align: center;
  margin-top: 1%;
}
</style>
